﻿using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using DynamicChart.Model;

namespace DynamicChart.Service.Step.Format;

public class SeriesStep : IFormatStep
{
    private readonly LoadService _loadService;

    public SeriesStep(LoadService loadService)
    {
        _loadService = loadService;
    }
    
    public void Process(IDictionary<string, object> param, IDictionary<string, object> data)
    {
        var rawData = data["rawData"] as IDictionary<string, object>;
        var legend = data["legendTemp"] as ISet<string>;
        var series = new List<Dictionary<string, object>>();
        var configs = new Dictionary<string, object>();

        if (param.TryGetValue("id", out var id) && id != null)
        {
            configs = _loadService.GetSeriesConfig(int.Parse(id.ToString()));
        }
        
        if (legend?.Count > 0)
        {
            series = legend.Select(legendKey =>
            {
                Dictionary<string, object> config = null;
                if (configs != null && configs.Count != 0)
                {
                    config = JsonSerializer.Deserialize<Dictionary<string, object>>(
                        configs[legendKey].ToString()!)!;
                }

                string defaultType = "line";
                string defaultBarWidth = "20%";
                object defaultSmooth = false;
                string defaultName = legendKey;
                
                return new Dictionary<string, object>
                {
                    ["id"] = Guid.NewGuid().ToString(),
                    ["lastestName"] = legendKey,
                    ["type"] = config?.GetValueOrDefault("type", defaultType) ?? defaultType,
                    ["barWidth"] = config?.GetValueOrDefault("barWidth", defaultBarWidth) ?? defaultBarWidth,
                    ["smooth"] = config?.GetValueOrDefault("smooth", defaultSmooth) ?? defaultSmooth,
                    ["name"] = config?.GetValueOrDefault("name", defaultName) ?? defaultName,
                    ["data"] = rawData.Keys
                        .Where(key => rawData[key] is IDictionary<string, object>)
                        .Select(key =>
                        {
                            var level2 = (IDictionary<string, object>)rawData[key];
                            return level2.TryGetValue(legendKey, out var val) ? val : 0;
                        })
                        .ToList()
                };
            }).ToList();
        }

        data["series"] = series;
    }
}
